<template>
  <div class="manage">
    <div class="box-top">
      <h1>你好{{user.username}}，欢迎使用本系统</h1>
    </div>
    <template>
      <el-carousel :interval="4000" type="card" height="300px">
        <el-carousel-item v-for="item in imgList" :key="item.id">
          <img style="object-fit: scale-down; width: 100%;height: 100%" :src="item.idView" class="image">
        </el-carousel-item>
      </el-carousel>
    </template>
    <div class="todo-calendar-container">
      <!-- 待办事项列表 -->
      <el-col :span="12" class="todo-list">
        <el-dialog
                :title="modelType===0?'新增' : '编辑'"
                :visible.sync="dialogVisible"
                width="50%"
                :before-close="handleClose">
          <el-form ref="form" :rules="rules" :model="form" label-width="120px" class="demo-form-inline">
            <el-form-item label="截止时间" prop="dueTime">
              <el-date-picker
                      v-model="form.dueTime"
                      clearable
                      type="datetime"
                      placeholder="截止时间"
                      align="right"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      :picker-options="pickerOptions"
                      @change="handleEndTimeChange">
              </el-date-picker>
              <!--            </div>-->
            </el-form-item>
            <el-form-item label="备忘录内容" prop="content">
              <el-input v-model="form.content" clearable placeholder="备忘录内容"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
        </el-dialog>
        <el-button style=" margin:0 0 10px 0" size="small" type="primary" @click="handleAdd">新增</el-button>
        <div class="common-table">
          <!-- max-height="380"  -->
          <el-table
                  :data="tableData"
                  stripe
                  style="width: 100%">
            <template slot="empty">
              <div><span>暂无数据，稍后重试</span></div>
            </template>
            <el-table-column
                    prop="dueTime"
                    label="截止时间"
                    width="100">
            </el-table-column>
            <el-table-column
                    prop="content"
                    label="备忘录内容"
                    width="280">
            </el-table-column>
            <el-table-column
                    fixed="right"
                    min-width="120"
                    label="操作">
              <template slot-scope="scope">
                <el-button
                        type="primary"
                        plain
                        size="mini"
                        @click="handleEdit(scope.$index, scope.row)">编辑
                </el-button>
                <el-button
                        plain
                        size="mini"
                        type="danger"
                        @click="handleDelete(scope.$index, scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--分页区-->
          <div class="block" style="margin:20px 0 0 15px ;">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="tablePage.pageNum"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="tablePage.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
          </div>
        </div>

      </el-col>

    <el-col :span="12" class="calendar">
      <div class="block-right">
        <el-calendar >
        </el-calendar>
      </div>
    </el-col>
    </div>
  </div>
</template>

<script>
  import {getTodoById,getTodosList,addTodos,updateTodos,deleteTodosById} from "@/api/Todos";

export default {
  name: 'home',
  data() {
    return {
      user:'',
      imgList:[
        {id:0,idView:require("@/assets/nmql.png")},
        {id:1,idView:require("@/assets/ql.png")},
        {id:2,idView:require("@/assets/qilai.png")},
      ],
      form: {
        userId:'',
        dueTime:'',
        content:''
      },
      tablePage: {
        pageNum: 1,//当前页
        pageSize: 8,//每页条数
      },
      tableData: [],
      total:0,
      rules: {},
      modelType: 0,
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      dialogVisible: false
    }
  },
  created() {
    this.user=JSON.parse(localStorage.getItem('user'))
    this.form.userId=user.id
    if (this.user===undefined || this.user===null){
      this.user={username:'游客'}
    }
    console.log(this.user,'这里是user本地存储')
  },
  methods: {
    getList() {
      const params = {
        pageNum: this.tablePage.pageNum,
        pageSize: this.tablePage.pageSize,
        userId: this.user.id
      }
      console.log(params, 'params')
      getTodosList({params}).then(res => {
        console.log(res, 'res')
        this.tableData = res.data.data
        this.total = res.data.total || 0
      }).catch(() => {
        this.$message.error('获取数据失败')
      })
    },
    submit() {
      this.$refs.form.validate((valid) => {
        console.log(valid, 'valid');
        if (valid) {
          if (this.modelType === 0) {
            addTodos(this.form).then(res => {
              if (res.data.code === 200) {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                });
                this.getList();
              } else {
                // 处理错误情况
                this.$message.error(res.data.message);
              }
              this.$refs.form.resetFields();
            }).catch(err => {
            })
          } else {
            console.log(this.form,'updateTodos')
            updateTodos(this.form).then(res => {
              if (res.data.code === 200) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
                this.getList();
              } else {
                // 处理错误情况
                this.$message.error(res.data.message);
              }
              this.$refs.form.resetFields();
              this.dialogVisible = false
            }).catch(err => {
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 弹窗关闭的时候调用
    handleClose() {
      // 清空表单
      this.form = {}
      this.dialogVisible = false
    },
    cancel() {
      this.handleClose()
    },
    handleEdit(index, row) {
      this.modelType = 1
      this.dialogVisible = true
      getTodoById(row.id).then(res => {
        console.log(res, 'res')
        this.form = res.data.data
      }).catch(() => {
      })
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTodosById(this.tableData[index].id).then(res => {
          if (res.data.code === 200) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getList();
          } else {
            // 处理错误情况
            this.$message.error(res.data.message);
          }
        }).catch(err => {
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleAdd() {
      this.dialogVisible = true
      this.modelType = 0
      this.form = {
        userId: this.user.id, // 确保 userId 被正确赋值
        dueTime: '',
        content: ''
      };
    },
    handleSizeChange(pageSize) {
      this.tablePage.pageSize = pageSize
      this.getList()//刷新数据
    },
    handleCurrentChange(currentPage) {
      this.tablePage.pageNum = currentPage
      this.getList()//刷新数据
    }
  },
  mounted() {
    this.getList()
  }
}
</script>

<style lang="less" scoped>

  .box-top{
    height: 40px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);//阴影
    border-radius: 10px;//圆角
    margin: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .todo-calendar-container {
    display: flex;
    justify-content: space-between;
    padding: 20px;
  }
  .todo-list {
    border-radius: 10px;
    margin: 10px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }
  .block-right{
    display: flex;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 10px;
    margin: 10px;
  }
</style>